package com.edu.controller.order.Carts;

import com.alibaba.fastjson2.JSONObject;
import com.edu.dto.ResultDto;
import com.edu.entity.OrderDetailEntity;
import com.edu.service.CartsService;
import com.edu.service.impl.CartsServiceImpl;
import com.edu.utils.ReturnCode;
import com.edu.utils.ServletHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * com.edu.controller.orders.Carts
 * 2024/7/11 8:57
 *
 * @author Fancy
 * @version 1.0
 */
@WebServlet("/carts/*")
public class OrderDetailController extends HttpServlet {
    CartsService cartsService = new CartsServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        JSONObject requestBodyAsJson = ServletHelper.getRequestBodyAsJson(req);
        OrderDetailEntity cart = new OrderDetailEntity();
        cart.setQuantity(requestBodyAsJson.getIntValue("quantity"));
        cart.setBookId(requestBodyAsJson.getIntValue("bookId"));

        int userId = Integer.parseInt(req.getPathInfo().substring(1));
        int cartItemId = cartsService.addToCart(cart, userId);
        HashMap<String, Integer> categoryIdMap = new HashMap<String, Integer>();
        categoryIdMap.put("cartItemId", cartItemId);

        try {
            if (cartItemId <= 0) {
                String rst = ResultDto.fail(ReturnCode.INTERNAL_SERVER_ERROR.getCode(), "添加失败");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.success(categoryIdMap);
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        int userId = Integer.parseInt(req.getPathInfo().substring(1));
        LinkedList<OrderDetailEntity> carts = cartsService.getCartItemByUserId(userId);

        try {
            if (carts == null) {
                String rst = ResultDto.fail(ReturnCode.INTERNAL_SERVER_ERROR.getCode(), "查询信息失败");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.success(carts);
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        String pathInfo = req.getPathInfo();
        String[] pathParts = pathInfo.split("/");
        int userId = Integer.parseInt(pathParts[1]);
        int cartItemId = Integer.parseInt(pathParts[2]);
        JSONObject requestBodyAsJson = ServletHelper.getRequestBodyAsJson(req);
        int quantity = requestBodyAsJson.getIntValue("quantity");
        System.out.println("userId: "+userId+" cartItemId: "+cartItemId+" quantity: "+quantity);
        int row = cartsService.updateCartItemQuantity(userId,cartItemId,quantity);

        try {
            if (row == 0) {
                String rst = ResultDto.fail(ReturnCode.INTERNAL_SERVER_ERROR.getCode(), "更新信息失败");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.success(null);
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        String pathInfo = req.getPathInfo();
        String[] pathParts = pathInfo.split("/");
        int userId = Integer.parseInt(pathParts[1]);
        int cartItemId = Integer.parseInt(pathParts[2]);
        System.out.println("userId: "+userId+" cartItemId: "+cartItemId+" quantity: ");
        int row = cartsService.deleteCartItem(userId,cartItemId);

        try {
            if (row == 0) {
                String rst = ResultDto.fail(ReturnCode.INTERNAL_SERVER_ERROR.getCode(), "从购物车移除商品失败");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.success(null);
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }
}
